﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

namespace netsoul
{
    public partial class FrmListeContact : Form
    {
        #region Variables
        
        Netsoul net;
        private bool Fconnected = false;
        dlgUpdateString dlgUpdateDebug = null;
        List<string> FUserChatList = new List<string>();
        List<FrmChat> FUserFrmList = new List<FrmChat>();

        #endregion Variables

        public FrmListeContact()
        {
            InitializeComponent();
            this.cbox_status.SelectedIndex = 0;
        }

        #region FormEvent

        private void btn_connect_Click(object sender, EventArgs e)
        {
            if (Fconnected == false)
            {
                if (Connection() == false)
                    return;
                cbox_status.Enabled = true;
                Fconnected = true;
                btn_connect.Text = "Deconnect";
                ThreadPool.SetMaxThreads(2, 2);
                ThreadPool.QueueUserWorkItem(this.ListenForUser, net);
                return;
            }
            else
            {
                net.Deconnection();
                Fconnected = false;
                btn_connect.Text = "Connect";
                txt_statut.Text = "Deconnecter";
                cbox_status.Enabled = false;
                return;
            }
        }

        private void btn_char_send_Click(object sender, EventArgs e)
        {
            int nb = 1;

            if (txt_char_user.Text.Trim().Length <= 0)
                return;
            if (txt_char_msg.Text.Trim().Length <= 0)
                return;

            if (Convert.ToInt32(txt_spam.Text) > 1)
                nb = Convert.ToInt32(txt_spam.Text);
            while (nb > 0)
            {
                net.Send_message_login(txt_char_user.Text, txt_char_msg.Text);
                nb--;
                txt_debug.Text += "\r\n" + nb;
                Thread.Sleep(300);
            }
            txt_char_msg.Text = string.Empty;
            txt_char_user.Text = string.Empty;
        }

        private void btn_detail_Click(object sender, EventArgs e)
        {
            Form Detail = new FrmDetail(net);
            Detail.Show();
        }

        private void optionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.OpenConfiguration();
        }

        #endregion FormEvent

        private bool Connection()
        {
            string login = Properties.Settings.Default.username;
            string password = Properties.Settings.Default.password;
            string host = Properties.Settings.Default.server;

            if (login.Length <= 0)
            {
                MessageBox.Show("Need login.");
                this.OpenConfiguration();
                return false;
            }
            if (password.Length <= 0)
            {
                MessageBox.Show("Need password");
                this.OpenConfiguration();
                return false;
            }
            //net = new Netsoul(this.txt_login.Text, this.txt_pass.Text, "10.42.1.59", 4242);
            net = new Netsoul(login, password, host, 4242);
            net.Location = Properties.Settings.Default.location;
            net.Data = Properties.Settings.Default.data;
            if (net.Register() == false)
            {
                txt_statut.Text = net.message_log;
                return false;
            }
            txt_statut.Text = "Connecter";
            Fconnected = true;
            return true;
        }

        private void OpenConfiguration()
        {
            using (FrmParam FormParam = new FrmParam())
            {
                DialogResult result = FormParam.ShowDialog();
            }
        }

        private void cbox_status_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (net != null && net.Connected == true)
                net.Change_status((nsStatus)(this.cbox_status.SelectedIndex));
        }

        #region Thread

        private delegate void dlgUpdateString(string txt);

        private void UpdateTxtDebug(string txt)
        {
            if (dlgUpdateDebug == null)
                dlgUpdateDebug = new dlgUpdateString(UpdateTxtDebug);
            if (this.InvokeRequired)
            {
                this.Invoke(dlgUpdateDebug, txt);
            }
            else
            {
                txt_debug.Text += txt + "\r\n";
            }
        }

        private int GetIndexChatWinOpen(string username)
        {
            if (FUserChatList == null || FUserChatList.Count == 1)
                return -1;
            for (int i = 0; i < FUserChatList.Count; i++)
            {
               if (FUserChatList[i].Split('@')[0].Contains(username.Split('@')[0]))
                  if (FUserChatList[i].Split('@')[1].Contains(username.Split('@')[1])
                     || username.Split( '@' )[1] == "*" || username.Split( '@' )[1].Length == 0)
                    return i;
            }
            return -1;
        }

        private void ListenForUser ( object Onet )
        {
           Netsoul net = (Netsoul)( Onet );
           string read = string.Empty;

           while ( Fconnected )
           {
               read = string.Empty;
               int fenetre;
               read = net.ReadLineSocket();
               UpdateTxtDebug( read );
               string[] tab = read.Split( '|' );
               string dest = string.Empty;
               if ( tab.Length > 1 )
               {
                   if ( tab[1].Trim().StartsWith( "msg" ) == true )
                   {
                       if ( tab[1].Trim().Split( ' ' ).Length == 2 )
                           dest = Netsoul.DecodeMSG( tab[1].Trim().Split( ' ' )[2].Split( '@' )[1].Trim() );
                       if ( dest == string.Empty || dest.Contains( net.Location.Trim() ) )
                       {
                           //427:user:1/3:khim_t@82.237.105.29:~:maison:epitech_2012 | msg qweqweq dst=*:khim_t@*On%20the%20network*
                           string login = tab[0].Trim().Split( ':' )[3].Split( '@' )[0].Trim();
                           string location = tab[0].Trim().Split( ':' )[5].Trim();
                           fenetre = GetIndexChatWinOpen( login + '@' + location );
                           if ( fenetre == -1 )
                           {
                               FUserChatList.Add( login + '@' + location );
                               FUserFrmList.Add( UserMsg( login, location, tab[1].Trim().Split( ' ' )[1], net ) );
                           }
                           else
                           {
                               if ( FUserFrmList[fenetre].Visible == false )
                               {
                                   UpdateUserMsg( fenetre );
                               }
                               FUserFrmList[fenetre].TxtChat = read.Split( '|' )[1].Trim().Split( ' ' )[1].Trim();
                           }
                       }
                       Thread.Sleep( 10 );
                   }

                   if ( tab[1].Trim().StartsWith( "login" ) == true )
                   {

                   }
               }
           }
        }

        private void UpdateUserMsg(int fenetre)
        {
            LaunchFormChat launch = new LaunchFormChat(FUserFrmList[fenetre]);
            Thread t = new Thread(new ThreadStart(launch.LaunchFormulaire));
            t.Start();
        }

        private FrmChat UserMsg(string login, string location, string msg, Netsoul pnet)
        {
            FrmChat user = new FrmChat(login, location, pnet);
            user.TxtChat = msg;
            LaunchFormChat launch = new LaunchFormChat(user);
            Thread t = new Thread(new ThreadStart(launch.LaunchFormulaire));
            t.Start();
            return user;
        }

        #endregion Thread

        private void btn_add_contact_Click ( object sender, EventArgs e )
        {
            if (txt_char_user.Text.Length > 0)
                net.SendCmd( txt_char_user.Text );
        }

    }

    public class LaunchFormChat
    {
        FrmChat Form;

        public LaunchFormChat(FrmChat f)
        {
            Form = f;
        }

        public void SetForm(FrmChat f)
        {
            Form = f;
        }

        public void LaunchFormulaire()
        {
            Form.ShowDialog();
        }
    }

    public class ListUserChats : ReadOnlyCollection<ListUserChat>
    {
        private int FNb_User;
        private int FNb_Online;

        public ListUserChats(IList<ListUserChat> liste)
            : base(liste)
        {
        }

        //public bool IsListed(string login)
        //{
        //}
    }

    public class ListUserChat : Netsoul
    {
        private FrmChat FChat;
        private string FLogin;
        private string FLocation;
        private string FIp;
        private string FData;
        private string FTxt;

        public ListUserChat() { }
        public ListUserChat(string login, string location, string ip, string data)
        {
            FLogin = login.Trim();
            FLocation = location.Trim();
            FIp = ip;
            FData = data;
        }
    }
}
